﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using ClosedXML.Excel;

#endregion

namespace ScrumTable.Common.Excel.OpenXmlSdk.Extensions
{
    /// <summary>
    /// Provides the additional functionalities required for Excel
    /// data management of a IXLCell instance.
    /// </summary>
    public static class XLCellUtil
    {
        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Returns true if the current cell contains a value.
        /// </summary>
        /// <param name="thisPtr">Specifies the pointer to the ClosedXml cell.</param>
        public static bool AccommodatesValue(this IXLCell thisPtr)
        {
            PreCondition.AssertNotNull(thisPtr, "thisPtr");

            if (string.IsNullOrEmpty(thisPtr.FormulaA1))
            {
                return (thisPtr.Value != null && !Equals(thisPtr.Value, string.Empty));
            }
            else
            {
                return !string.IsNullOrEmpty(thisPtr.ValueCached);
            }
        }

        /// <summary>
        /// Returns the value of the given cell and avoids an empty string by returning
        /// a null pointer instead.
        /// </summary>
        /// <param name="thisPtr">Specifies the pointer to the ClosedXml cell.</param>
        public static object GetValueAvoidEmpty(this IXLCell thisPtr)
        {
            PreCondition.AssertNotNull(thisPtr, "thisPtr");

            object cellValue = (thisPtr.IsCalculated()) ? thisPtr.ValueCached : thisPtr.Value;

            if (Equals(cellValue, string.Empty))
            {
                return null;
            }
            return cellValue;
        }

        /// <summary>
        /// Returns true if the value of the current field is calculated by a formula.
        /// </summary>
        /// <param name="thisPtr">Specifies the pointer to the ClosedXml cell.</param>
        public static bool IsCalculated(this IXLCell thisPtr)
        {
            PreCondition.AssertNotNull(thisPtr, "thisPtr");

            return (!string.IsNullOrEmpty(thisPtr.FormulaA1));
        }

        #endregion
    }
}